package com.mulong.mall.service.impl;

import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSON;
import com.mulong.common.dao.mall.mapper.GatewayAccountMapper;
import com.mulong.common.domain.pojo.mall.custom.CustomGatewayAccount;
import com.mulong.common.enums.GatewayAccountStatus;
import com.mulong.common.exception.ErrorEnums;
import com.mulong.common.exception.MulongException;
import com.mulong.common.util.MulongUtil;
import com.mulong.mall.domain.bo.AccessToken;
import com.mulong.mall.domain.param.OauthTokenParam;
import com.mulong.mall.domain.result.OauthTokenResult;
import com.mulong.mall.service.OauthService;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * OauthServiceImpl
 * 
 * @author mulong
 * @data 2021-08-10 18:01:14
 */
@Slf4j
@Service
public class OauthServiceImpl implements OauthService {
    @Autowired
    private GatewayAccountMapper gatewayAccountMapper;

    /**
     * 获取token
     * 
     * @author mulong
     */
    @Override
    public OauthTokenResult token(OauthTokenParam param) {
        String username = param.getUsername();
        String password = param.getPassword();
        CustomGatewayAccount gatewayAccount = gatewayAccountMapper.selectByUsername(username);
        if (gatewayAccount == null) {
            log.error("cannot find gateway account, username [{}]", username);
            throw new MulongException(ErrorEnums.GET_ACCESS_TOKEN_FAILED);
        }
        if (!GatewayAccountStatus.ENABLED.getCode().equals(gatewayAccount.getStatus())) {
            log.error("gateway account does not enabled, username [{}]", username);
            throw new MulongException(ErrorEnums.GET_ACCESS_TOKEN_FAILED);
        }
        if (!password.equals(gatewayAccount.getPassword())) {
            log.error("password mismatch, username [{}] password [{}] gateway account password [{}]", username, password, gatewayAccount.getPassword());
            throw new MulongException(ErrorEnums.GET_ACCESS_TOKEN_FAILED);
        }
        Date now = new Date();
        Integer expiresIn = 60*60*24;
        Date expiredTime = DateUtil.offsetSecond(now, expiresIn);
        AccessToken accessToken = new AccessToken();
        accessToken.setGatewayAccountId(gatewayAccount.getId());
        accessToken.setUsername(username);
        accessToken.setUsertype(gatewayAccount.getType());
        accessToken.setExpiredTime(expiredTime);
        OauthTokenResult oauthTokenResult = new OauthTokenResult();
        oauthTokenResult.setAccessToken(MulongUtil.desEncrypt(JSON.toJSONString(accessToken)));
        oauthTokenResult.setExpiredTime(expiredTime);
        return oauthTokenResult;
    }

}
